import {Component, OnInit} from '@angular/core';
import {UserService} from './user.service';
import {User} from './user.model';
import {BsModalRef, BsModalService} from 'ngx-bootstrap';
import {UserEditComponent} from './user-edit/user-edit.component';
import {ToastrService} from 'ngx-toastr';

@Component({
  selector: 'app-user-manage',
  templateUrl: './user-manage.component.html'
})
export class UserManageComponent implements OnInit {
  users: Array<User> = [];

  bsModalRef: BsModalRef;

  constructor(private userService: UserService,
              private modalService: BsModalService,
              private toastr: ToastrService) {
  }

  ngOnInit() {
    this.userService.findAll().subscribe(data => {
      if (data['success']) {
        this.users = data['data'];
      }
    });
  }

  //按钮的click执行函数，打开一个子模块
  modifyUser(user: User) {
    //给子组件的成员赋值，如果子组件中含有list、title同名成员，则自动进行了赋值
    const initialState = {
      title: '编辑用户',
      isAdd: false,
      user: user
    };
    this.bsModalRef = this.modalService.show(UserEditComponent, {initialState});//显示子组件
    this.modalService.onHidden.subscribe((r: string) => {
      // 子组件关闭后，触发的订阅函数
      // this.bsModalRef.content代表子组件对象，isCancel是子组件中的一个成员，可以直接访问
      if (!this.bsModalRef.content.isCancel) {
        this.userService.modify(this.bsModalRef.content.user).then(data => {
          if (data['success']) {
            this.toastr.success('用户信息已修改', '修改成功!');
          } else {
            this.toastr.error(data['errorMsg'], '修改失败!');
          }
        });
      }
    });
  }

  addUser() {
    //给子组件的成员赋值，如果子组件中含有list、title同名成员，则自动进行了赋值
    const initialState = {
      title: '添加用户',
      isAdd: true,
      user: new User()
    };
    this.bsModalRef = this.modalService.show(UserEditComponent, {initialState});//显示子组件
    this.modalService.onHidden.subscribe((r: string) => {
      // 子组件关闭后，触发的订阅函数
      // this.bsModalRef.content代表子组件对象，isCancel是子组件中的一个成员，可以直接访问
      if (!this.bsModalRef.content.isCancel) {
        this.userService.addUser(this.bsModalRef.content.user).then(data => {
          if (data['success']) {
            this.toastr.success('用户已添加', '添加成功!');
          } else {
            this.toastr.error(data['errorMsg'], '添加失败!');
          }
        });
      }
    });
  }

  delete(user: User) {
    this.userService.delete(user.id).then(data => {
      if (data['success']) {
        this.toastr.success('用户已删除', '删除成功!');
      } else {
        this.toastr.error(data['errorMsg'], '删除失败!');
      }
    });
  }
}
